package com.xsp.util;

import java.io.IOException;
import java.io.InputStream;
import java.sql.*;
import java.util.Properties;

/**
 * @author jay
 * @date 2023/12/20
 * @desc
 */
public class DBHelper {
    private static String url;
    private static String username;
    private static String password;
    private static String driverClassName;

    // 从配置文件读取数据库的连接配置信息
    static {
        Properties properties = new Properties();
        InputStream inputStream = DBHelper.class.getClassLoader()
                .getResourceAsStream("book.properties");
        try {
            properties.load(inputStream);
            url = properties.getProperty("jdbc.url");
            username = properties.getProperty("jdbc.username");
            password = properties.getProperty("jdbc.password");
            driverClassName = properties.getProperty("jdbc.driverClassName");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static Connection getConnection() throws ClassNotFoundException, SQLException {
        Class.forName(driverClassName);
        return DriverManager.getConnection(url, username, password);
    }

    public static void close(Connection connection) throws SQLException {
        if (connection != null) {
            connection.close();
        }
    }

    public static void close(Statement statement, Connection connection) throws SQLException {
        if (statement != null) {
            statement.close();
        }
        if (connection != null) {
            connection.close();
        }
    }

    public static void close(ResultSet resultSet, Statement statement, Connection connection) throws SQLException {
        if (resultSet != null) {
            resultSet.close();
        }
        if (statement != null) {
            statement.close();
        }
        if (connection != null) {
            connection.close();
        }
    }

    /**
     * 通用的执行增删改的方法
     *
     * @param sql
     * @param params
     * @return
     */
    public static int executeUpdate(String sql, Object... params)
            throws SQLException, ClassNotFoundException {
        Connection connection = null;
        PreparedStatement statement = null;

        try {
            connection = DBHelper.getConnection();
            statement = connection.prepareStatement(sql);

            if (params != null) {
                for (int i = 0; i < params.length; i++) {
                    statement.setObject(i + 1, params[i]);
                }
            }

            return statement.executeUpdate();
        } catch (ClassNotFoundException | SQLException e) {
            e.printStackTrace();
            throw e;
        } finally {
            try {
                DBHelper.close(statement, connection);
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        }
    }
}
